//
//  ClassifySectionVC.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/1/3.
//  Copyright © 2020年 sun. All rights reserved.
//

#import "ClassifySectionVC.h"
#import "ClassifyBarCell.h"
#import "ClassifySectionCell.h"
#import "UIView+GradientLayer.h"
#import "ProductDetailVC.h"

#pragma mark -- mark Model
#import "ProductModel.h"

@interface ClassifySectionVC ()<UICollectionViewDelegate, UICollectionViewDataSource> {
    BOOL _sequencePositive; // 正序
    NSInteger _page; // 分页
    NSString *_shopLabel; // 标签
    UIButton *_fliterBtn; // 修改button 图片文字展示
}
@property (nonatomic, strong) UICollectionView *productCollectionView;
@property (nonatomic, strong) UICollectionView *barCollectionView;

@property (nonatomic, strong) NSArray <ProductLabelDetailModel *>*barArray;
@property (nonatomic, strong) NSArray <ProductDetailModel *>*dataArray;
@end
static NSString *const ptIdentifier = @"pt_identifier";
static NSString *const barIdentifier = @"bar_identifier";
@implementation ClassifySectionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = SKColorWithHex(0xF7F7F7);
//    [self initNavBarButtonItem];
    [self initContentViews];
    _sequencePositive = true; // 默认正序
    _page = 1;
    [self requestData];
}

- (void)initNavBarButtonItem {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"shop_share_bar_btn_img"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(shareBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [self setGk_navRightBarButtonItem:barButton];
}

- (void)initContentViews {
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sortButton.titleLabel.font = SKFONT_SIZE(13);
    [sortButton setTitle:@"排序筛选" forState:UIControlStateNormal];
    [sortButton setTitleColor:SKColorWithHex(0x333333) forState:UIControlStateNormal];
    [sortButton setImage:SKIMAGE_NAMED(@"auction_fliter_fall") forState:UIControlStateNormal];
    [sortButton setImage:SKIMAGE_NAMED(@"auction_fliter_up") forState:UIControlStateSelected];
    [sortButton addTarget:self action:@selector(sortButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    sortButton.backgroundColor = SKColorWithHex(0xE4E4E4);
    
    CGFloat labelWidth = sortButton.titleLabel.intrinsicContentSize.width;
    CGFloat imageWidth = sortButton.imageView.frame.size.width;
    sortButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth - 10, 0, imageWidth + 10);
    sortButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0,  -labelWidth);
    
    [self.view addSubview:sortButton];
    
    [sortButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.top.mas_offset(SKTopBar_Height);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(89.0/375);
        make.height.mas_equalTo(sortButton.mas_width).multipliedBy(45.0/89);
    }];
    
    [self.barCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(sortButton.mas_right).mas_offset(0);
        make.top.bottom.mas_equalTo(sortButton);
        make.right.mas_offset(0);
    }];
    
    [self.productCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(sortButton.mas_bottom).mas_offset(0);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    
    self.productCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.productCollectionView.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreProductList)];
    
}

#pragma mark -- mark 懒加载

- (UICollectionView *)productCollectionView {
    if (!_productCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat margin = 15.0;
        CGFloat centerMargin = 5.0;
        CGFloat width = (self.view.width - margin * 2 - centerMargin) * 0.5;
        CGFloat height = width / 170.0 * 228;
        layout.itemSize = CGSizeMake(width, height);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = centerMargin;
        layout.minimumInteritemSpacing = centerMargin;
        layout.sectionInset = UIEdgeInsetsMake(0, margin, centerMargin, margin);
        _productCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _productCollectionView.showsVerticalScrollIndicator = false;
        _productCollectionView.showsHorizontalScrollIndicator = false;
        [_productCollectionView registerClass:[ClassifySectionCell class] forCellWithReuseIdentifier:ptIdentifier];
        _productCollectionView.delegate = self;
        _productCollectionView.dataSource = self;
        _productCollectionView.backgroundColor = self.view.backgroundColor;
        _productCollectionView.scrollEnabled = true;
        [self.view addSubview:_productCollectionView];
    }
    return _productCollectionView;
}

- (UICollectionView *)barCollectionView {
    if (!_barCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat margin = 12.0;
        CGFloat top = 8.5;
        CGFloat bottom = top;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = margin;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(top, margin, bottom, margin);
        layout.itemSize = CGSizeMake(80, (45.0/375) * self.view.width - top - bottom);
        _barCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _barCollectionView.showsHorizontalScrollIndicator = false;
        _barCollectionView.showsVerticalScrollIndicator = false;
        _barCollectionView.delegate = self;
        _barCollectionView.dataSource = self;
        [_barCollectionView registerClass:[ClassifyBarCell class] forCellWithReuseIdentifier:barIdentifier];
        _barCollectionView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_barCollectionView];
    }
    return _barCollectionView;
}

#pragma mark -- mark UICollectionViewDelegate UICollectionViewDataSource

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.barCollectionView) {
        // 按钮
        ClassifyBarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:barIdentifier forIndexPath:indexPath];
        ProductLabelDetailModel *model = self.barArray[indexPath.item];
        cell.title = model.title;
        return cell;
    }else {
        // 详情
        ClassifySectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ptIdentifier forIndexPath:indexPath];
        ProductDetailModel *model = self.dataArray[indexPath.item];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:SKIMAGE_NAMED(@"cell_default_img")];
        cell.title = model.name;
        cell.price = model.price;
        SKWeakSelf;
        cell.shareButtonClickBlock = ^{
            [weakSelf cellShareButtonClick:indexPath];
        };
        return cell;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.barCollectionView) {
        return self.barArray.count;
    }else {
        return self.dataArray.count;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.barCollectionView) {
        // 点击标题
        [self barButtonClickWith:indexPath];
    }else {
        // 点击商品
        [self showProductDetailWith:indexPath];
    }
}


#pragma mark -- mark 网络数据

- (void)requestData {
    [self requestShopLabels];
}

///  获取标签
- (void)requestShopLabels {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getShopLabel" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        ProductLabelModel *model = [ProductLabelModel modelWithDictionary:response];
        NSString *labelText;
        if ([model isSuccess]) {
            // 获取标签 成功
            labelText = [model.data firstObject].ID;
            weakSelf.barArray = [model.data sortedArrayUsingComparator:^NSComparisonResult(ProductLabelDetailModel  *obj1, ProductLabelDetailModel *obj2) {
                return self->_sequencePositive ? ([obj1.sort intValue] < [obj2.sort intValue]) : ([obj1.sort intValue] >= [obj2.sort intValue]);
            }];
            [weakSelf.barCollectionView reloadData];
        }else {
            // 获取标签失败
        }
        [weakSelf requestProductListWith:self.typeId AndShopLabel:labelText];
    } failBlock:^(NSError *error) {
        [weakSelf requestProductListWith:self.typeId AndShopLabel:nil];
    }];
}

/// 获取数据列表
/// @param typeId 类型id
/// @param shopLabel 商铺标签
- (void)requestProductListWith:(NSString *)typeId AndShopLabel:(NSString *)shopLabel {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (typeId) {
        [param addEntriesFromDictionary:@{@"type_two_id":@([typeId intValue])}];
    }
    if (shopLabel) {
        [param addEntriesFromDictionary:@{@"label_id":@([shopLabel intValue])}];
        _shopLabel = shopLabel; // 记录shopLabel
    }
    NSString *page = [NSString stringWithFormat:@"%lu", (long)_page];
    [param addEntriesFromDictionary:@{@"page":page}];
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getGoodsList" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        ProductModel *model = [ProductModel modelWithDictionary:response];
        if ([model isSuccess]) {
            // 获取数据成功
            if ([page isEqualToString:@"1"]) {
                // 下拉刷新
                weakSelf.dataArray = model.data;
            }else {
                // 上拉加载
                NSMutableArray *mArr = [NSMutableArray<ProductDetailModel *> arrayWithArray:weakSelf.dataArray];
                [mArr addObjectsFromArray:model.data];
                weakSelf.dataArray = mArr;
            }
            weakSelf.dataArray = [weakSelf.dataArray sortedArrayUsingComparator:^NSComparisonResult(ProductDetailModel *obj1, ProductDetailModel *obj2) {
                return self->_sequencePositive ? ([obj1.ptId intValue] < [obj2.ptId intValue]) : ([obj1.ptId intValue] < [obj2.ptId intValue]);
            }];
            [weakSelf.productCollectionView reloadData];
        }else {
            // 获取数据失败
            [weakSelf showMessage:model.msg];
        }
        if ([self.productCollectionView.mj_header isRefreshing]) {
            [self.productCollectionView.mj_header endRefreshing];
        }
        if ([self.productCollectionView.mj_footer isRefreshing]) {
            [self.productCollectionView.mj_footer endRefreshing];
        }
    } failBlock:^(NSError *error) {
        [self debugShowMessage:error.localizedDescription];
        if ([self.productCollectionView.mj_header isRefreshing]) {
            [self.productCollectionView.mj_header endRefreshing];
        }
        if ([self.productCollectionView.mj_footer isRefreshing]) {
            [self.productCollectionView.mj_footer endRefreshing];
        }
    }];
}

///  获取更多数据
- (void)requestMoreProductList {
    if (!self.dataArray.count) {
        if ([self.productCollectionView.mj_footer isRefreshing]) {
            [self.productCollectionView.mj_footer endRefreshing];
        }
    }
    _page++;
    [self requestShopLabels];
}



#pragma mark -- mark EVENT

/**
 筛选排序
 
 @param sender sender
 */
- (void)sortButtonClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    _sequencePositive = sender.isSelected;
    [self requestData];
}

/**
 分享
 
 @param sender sender
 */
- (void)shareBarButtonClick:(UIButton *)sender {
    
}

#pragma mark -- mark 业务逻辑

/**
 标题点击事件
 
 @param indexPath indexPath
 */
- (void)barButtonClickWith:(NSIndexPath *)indexPath {
    ProductLabelDetailModel *model = self.barArray[indexPath.item];
    _shopLabel = model.ID;
    [self requestProductListWith:self.typeId AndShopLabel:model.ID];
}

/**
 查看商品详情
 
 @param indexPath indexPath
 */
- (void)showProductDetailWith:(NSIndexPath *)indexPath {
    ProductDetailModel *model = self.dataArray[indexPath.item];
    ProductDetailVC *vc = [[ProductDetailVC alloc] init];
    vc.type = 0;
    vc.ptId = model.ptId;
    vc.showType = ProductDetailTypeDetail;
    [self.navigationController pushViewController:vc animated:YES];
}


/**
 cell 分享按钮点击回调
 
 @param indexPath indexPath
 */
- (void)cellShareButtonClick:(NSIndexPath *)indexPath {
    
}
@end
